﻿/*
XsltDb is powerful XSLT module for DotnetNuke.
It offers safe database access, SEO-friendly AJAX support,
visitor interactions, environment integration (dnn properties,
request, cookie, session and form values), regular expressions, etc.

Author:
 
    Anton Burtsev
    burtsev@yandex.ru

Project home page: 
 
    http://xsltdb.codeplex.com
*/

var mdo_PageLoadedAt = new Date();

function mdo_fire(prms, self_cli)
{
    if ( prms == null )
        return;

    var subs = {};
    for ( var p in prms ) {
        var pName = prms[p];
        if ( pName.indexOf("$") === 0 ) {
            var search = "watch-" + pName.substring(1) + "-";
            jQuery("span[id^='" + search + "']").each(function (i) {
                var cli = this.id.split("-")[2];
                if (cli == self_cli) return;
                subs[cli] = cli;
            });
        }
    }
    for (var cli in subs)
        mdo_ajax(cli);
}

function mdo_set_comm(cli, map) {

    if ( map == null )
        return;

    for ( var pName in map )
    {
        var pVal = map[pName];

        if ( pVal == null )
            pVal = "";

        var hid;
        if ( pName.indexOf("$") === 0 )
           hid = document.getElementById("XsltDbGlobals");
        else
           hid = document.getElementById("mdo-hid-" + cli + "-value");

        if ( hid == null )
            return;

        pName = escape(pName);
        pVal = escape(pVal);

        var qs = "&" + hid.value;
        var regex = new RegExp("(&" + pName + "=)([^&]*)");

        if (qs.match(regex) == null)
        {
            if ( qs.length > 1 )
                qs += "&" + pName + "=" + pVal;
            else
                qs = pName + "=" + pVal;
        }
        else
            qs = qs.replace(regex, "$1" + pVal);

        if (qs.indexOf("&") === 0)
            qs = qs.substring(1);

        hid.value = qs;
    }
}

function mdo_serialize(p)
{
    jQuery("input,select,textarea").each(function(i) {

        if (this.name == "" || this.name == null || this.value == "" || this.value == null)
            return;
        if (this.name == "__VIEWSTATE")
            return;
        if (this.name.indexOf("__dnn") == 0)
            return;

        if ( (this.type == "checkbox" || this.type == "radio" ) && !this.checked)
            return;

        if (p[this.name])
            p[this.name] += "," + this.value;
        else
            p[this.name] = this.value;
    });
}

function mdo_ajax(cli, map, validator) {
    if (validator != null && !validator()) return;
    mdo_ajax_comm(cli, map);
}
function mdo_submit(cli, map, validator) {
    if (validator != null && !validator()) return;
    mdo_set_comm(cli, map);
    __doPostBack(cli.replace("_", "$"), "");
}

function __mdo_appendQS(qs, what) {
    return (qs ? qs + "&" : "?") + what;
}

function mdo_ajax_comm(cli, map) {

    mdo_set_comm(cli, map);

    var p = {};

    p["TabID"] = XsltDbModRepository[cli].TabID;
    p["ModuleID"] = XsltDbModRepository[cli].ModuleID;
    p["TabModuleID"] = XsltDbModRepository[cli].TabModuleID;
    p["XsltDb_js_window_location"] = window.location.toString();
    p["XsltDb_SkinPath"] = mdo_SkinPath;
    p["ConfigID"] = XsltDbModRepository[cli].ConfigID;
    p["XsltDbClientID"] = cli;
    mdo_serialize(p);

    var search = window.location.search;

    if (search.toLowerCase().indexOf("tabid") < 0)
        search = __mdo_appendQS(search, "tabid="+p.TabID);

    if (mdo_PortalAlias)
        search = __mdo_appendQS(search, "alias=" + encodeURIComponent(mdo_PortalAlias));

    jQuery.ajax({
        url: mdo_ApplicationPath + "/DesktopModules/XsltDb/ajax.ashx" + search,
        data: p,
        type: 'POST',
        dataType: 'text',
        async: true,
        success: function (data, textStatus, http) {

            var newvalue = http != null ? http.responseText : data;
            if (newvalue != "mdo-live-nothing-changed-marker") {
                var newhash = "";
                var mode = map ? map["@mdo-live-refresh"] : null;
                var xspanId = "xsltdb-smart-live-vs-" + cli;
                var xdivId = "xsltdb-" + cli;
                var xdiv = jQuery("#" + xdivId);
                var xspan = xdiv.find("#" + xspanId);
                if (mode == "smart") {
                    NewHashRX = new RegExp("(?:<span\\s+id\\s*=\\s*\"xsltdb-smart-live-vs-.+?\"\\s+state\\s*=\\s*\")([^\"]+)(?:\")");
                    var m = newvalue.match(NewHashRX);
                    if (m) newhash = m[1];
                    var oldhash = xspan.size() > 0 ? xspan.attr("state") : "";
                    if (oldhash != newhash)
                        xdiv.html(newvalue);
                }
                else {
                    xdiv.html(newvalue);
                }
            }
            if (map != null) {
                var prms = new Array();
                for (var pName in map)
                    prms[prms.length] = pName;

                mdo_fire(prms, cli);

                if (map != null) {
                    var m = {};
                    for (var k in map)
                        if (k.indexOf("@") === 0)
                            m[k] = "";
                    mdo_set_comm(cli, m);
                }
            }
        }
    });
}

function mdo_live_gethash(cli) {
    try {
        return jQuery("#xsltdb-" + cli).find("#xsltdb-smart-live-vs-" + cli).attr("state");
    } catch (ex) { return ""; }
}

function mdo_refresh_module(guid, map, validator) {
    if (validator != null && !validator()) return;
    for (var cli in XsltDbModRepository) {
        if (XsltDbModRepository[cli].ConfigID.toLowerCase() == guid.toLowerCase())
            mdo_ajax_comm(cli, map, validator);
    }
}

function mdo_handler_comm(cli, p, callable, callback) {

    p["TabID"] = XsltDbModRepository[cli].TabID;
    p["ModuleID"] = XsltDbModRepository[cli].ModuleID;
    p["TabModuleID"] = XsltDbModRepository[cli].TabModuleID;
    p["XsltDb_js_window_location"] = window.location.toString();
    p["XsltDb_SkinPath"] = mdo_SkinPath;
    p["ConfigID"] = XsltDbModRepository[cli].ConfigID;
    p["XsltDbClientID"] = cli;

    if (callable)
        p["XsltDbCallable"] = callable;

    mdo_serialize(p);

    var search = window.location.search;
    if (search.toLowerCase().indexOf("tabid") < 0)
        search = __mdo_appendQS(search, "tabid=" + p.TabID);

    if (mdo_PortalAlias)
        search = __mdo_appendQS(search, "alias=" + encodeURIComponent(mdo_PortalAlias));

    var result = jQuery.ajax({
        url: mdo_ApplicationPath + "/DesktopModules/XsltDb/ajax.ashx" + search,
        data: p,
        type: 'POST',
        dataType: 'text',
        async: callback != null,
        success: function(data, textStatus, http) { if (callback != null) callback(http != null ? http.responseText : data); }
    });

    if ( callback )
        return null;

    return result.responseText;
}

function mdo_falert(msg) {
    alert(msg);
    return false;
}

function mdo_enter(e, callback) {
    var code = e.charCode == null || e.charCode == 0 ? e.keyCode : e.charCode;
    if (code == 13) {
        try {
            if (callback) callback();
        } catch (ex) { }
        return false;
    }
    return true;
}

function mdo_loadXMLDoc(dname) {
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    }
    else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET", dname, false);
    xhttp.send("");
    return xhttp.responseXML;
}

function mdo_parseXMLDoc(xml) {
    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xml, "text/xml");
    }
    else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xml);
    }

    return xmlDoc;
}

function mdo_xslt_transform(xsl, xml, params)
{
    var xmlTester = /^\s*</;
    
    if (xmlTester.test(xml))
        xml = mdo_parseXMLDoc(xml);
    else
        xml = mdo_loadXMLDoc(xml);
        
    if (xmlTester.test(xsl))
        xsl = mdo_parseXMLDoc(xsl);
    else
        xsl = mdo_loadXMLDoc(xsl);
        
    // code for IE
    if (window.ActiveXObject) {
        if (params != null)
            for (var key in params)
                xsl.selectSingleNode("/xsl:stylesheet/xsl:param[@name='" + key + "']").text = params[key];
        return xml.transformNode(xsl);
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument) {
        xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);
        if (params != null)
            for (var key in params)
                xsltProcessor.setParameter(null, key, params[key]);
        resultDocument = xsltProcessor.transformToFragment(xml, document);
        return (new XMLSerializer()).serializeToString(resultDocument)
    } 
}


//////////////////////////////// COOKIE STUFF ////////////////////////////////

function mdo_create_cookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expires + "; path=/";
}
function mdo_read_cookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}
function mdo_erase_cookie(name) {
    mdo_create_cookie(name, "", -1);
}
//////////////////////////////// COOKIE STUFF ////////////////////////////////